package com.lagou.config;

import com.lagou.MyRunBoot;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.io.File;
import java.io.IOException;

/**
 * @ClassName: SpringApplication
 * @Description:
 * @Author: qjc
 * @Date: 2021/8/25 12:58 下午
 */
public class SpringApplication {

    private Class<?>[] primarySources;

    public SpringApplication(Class<?>[] primarySources) {
        this.primarySources = primarySources;
    }

    public static void run(Class<?> primarySources,String[] args) {
        new SpringApplication(new Class[]{primarySources}).run(args);
    }

    private Integer port = 1111;

    public void run(String... args) {
        // 创建并启动Tomcat
        File baseDirectory = null;
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);
        try {
            File baseDir = baseDirectory != null ? baseDirectory : createTempDir("tomcat");
            tomcat.addWebapp("/", "/var");
            tomcat.setBaseDir(baseDir.getAbsolutePath());
            tomcat.start();
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    File createTempDir(String prefix) throws Exception {
        try {
            File tempDir = File.createTempFile(prefix + ".", "." + port);
            tempDir.delete();
            tempDir.mkdir();
            tempDir.deleteOnExit();
            return tempDir;
        } catch (IOException var3) {
            throw new Exception("Unable to create tempDir. java.io.tmpdir is set to " + System.getProperty("java.io.tmpdir"), var3);
        }
    }

}
